package csv

import (
	"encoding/csv"
	"fmt"
	"io"
	"os"
)

// ReadCSV 读取CSV文件
func ReadCSV() {

	f, err := os.Open("data.csv")
	if err != nil {
		fmt.Println("open csv file err：", err.Error())
	}

	defer f.Close()

	reader := csv.NewReader(f)

	// 一次性将文件内容全部读取出来
	records, err := reader.ReadAll()
	if err != nil {
		fmt.Println("readAll csv file err：", err.Error())
	}

	fmt.Println(records)

	// 每次读取一条记录（不能两种读取方式都使用，因为指针已经走到了最后）
	for {
		record, err := reader.Read()
		if err != nil || err == io.EOF {
			break
		}
		fmt.Println(record)
	}
}

// WriteCSV 写CSV文件
func WriteCSV() {
	f, err := os.Create("data.csv")
	if err != nil {
		fmt.Println("create csv file err：", err.Error())
	}

	writer := csv.NewWriter(f)

	var header = []string{"name", "age", "height", "weight"}
	if err := writer.Write(header); err != nil {
		fmt.Println("write csv header info err：", err.Error())
	}

	var data = [][]string{{"wcj", "24", "172", "62.5"}, {"bss", "27", "155", "49"}, {"hhy", "24", "162", "48"}}
	if err := writer.WriteAll(data); err != nil {
		fmt.Println("write csv data info err：", err.Error())
	}
}

// TestCSV 测试CSV文件读写
func TestCSV() {
	WriteCSV()
	ReadCSV()
}
